<template>
  <div class="group-chat-room">
    <!-- 群聊头部信息 -->
    <div class="chat-header">
      <h3>{{ currentGroup?.name || '群聊' }}</h3>
      <span class="group-desc">{{ currentGroup?.desc || '' }}</span>
      <span v-if="currentGroup?.unreadCount > 0" class="unread-count">{{ currentGroup.unreadCount }}</span>
    </div>

    <!-- 聊天消息显示区域 -->
    <div class="chat-messages" v-if="currentGroup">
      <div
        v-for="(message, index) in currentGroup.messages"
        :key="index"
        :class="['chat-message', { 'self-message': message.sender === username}]"
      >
        <img
          :src="message.sender === username ? 'https://picsum.photos/30/30' : currentGroup.avatar"
          alt="Avatar"
          class="message-avatar"
        />
        <div class="message-wrapper">
          <!-- 只有别人发的消息才显示发送者名称 -->
          <div  class="message-sender">
            {{ message.sender }}
          </div>
          <div class="message-content">
            <span>{{ message.content }}</span>
          </div>
          <div class="message-time">
            {{ message.time }}
          </div>
        </div>
      </div>
    </div>

    <!-- 消息输入框和发送相关区域 -->
    <div class="message-input-area" v-if="currentGroup">
      <!-- 新增的图标区域，留出空间并添加图标 -->
      <div class="icon-section">
        <!-- 使用导入的PNG图片 -->
        <img :src="smileImg" alt="Smile" class="smile-icon" @click="openEmojiPicker" />
        <img :src="fileUploadImg" alt="File Upload" class="file-upload-icon" @click="openFilePicker" />
        <i class="fa-regular fa-file" @click="openFilePicker" />
      </div>
      <!-- 消息输入框和发送按钮区域 -->
      <div class="input-and-send">
        <textarea
          v-model="newMessage"
          placeholder="输入消息..."
          class="message-input"
        ></textarea>
        <button @click="sendMessage" class="send-button">发送</button>
      </div>
    </div>
    <div v-else class="no-group-selected">请选择一个群聊开始聊天</div>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useGroupStore } from '@/stores/group';
import smileImg from '@/assets/icons/smile.png';
import fileUploadImg from '@/assets/icons/file_upload.png';

const route = useRoute();
const groupStore = useGroupStore();
const username = ref();

const groupId = ref(route.query.groupId);
const groupName = ref(route.query.groupName)
const createBy = ref(route.query.createBy);
const currentGroup = ref(null);
const newMessage = ref('');

// 从 Pinia store 中获取群聊列表
const groups = groupStore.groups;
console.log("groups2：",groups);
// 监听 groupId 的变化，更新当前群聊
watch(() => route.query.groupId, (newId) => {
  console.log('groupId变化:', newId);
  groupId.value = newId;
  console.log("groupId2：",groupId.value)
});

watch(() => route.query.groupName, (newId) => {
  console.log('groupName变化:', newId);
  groupName.value = newId;
  console.log("groupName2：",groupName.value)
});

watch(() => route.query.createBy, (newId) => {
  console.log('createBy变化:', newId);
  createBy.value = newId;
  console.log("createBy2",createBy.value)
});


watchEffect(() => {
  if (groupName.value!=undefined) {
    const target = groups.find(g => g.name === groupName.value);
    if (target) {
      currentGroup.value = target;
    }else{
      groupStore.addGroup({
        id: groupId.value,
        name: groupName.value,
        avatar: 'https://picsum.photos/70/70',
        messages: [],
        members: [],
        owner: createBy.value,
        unreadCount: 0,
        isMuted: false // 已静音
      })
      currentGroup.value = groups.find(g=>g.name === groupName.value)
    }
  } else {
    console.log("group is null")
    currentGroup.value = null;
  }
});

onMounted(() => {
  console.log("groups1：",groups);
  // 假设从主进程获取用户名
  window.electronAPI.getUsername().then((res) => {
    username.value = res;
  });

  // 监听群聊消息
  // window.electronAPI.socket.onMessage((msgStr) => {
  //   const msgWrapper = msgStr;
  //   const contentObj = msgWrapper.content;
  //   console.log("contentObj",contentObj)
  //   if (
  //     msgWrapper.type === 2 &&
  //     currentGroup.value &&
  //     contentObj.groupId === currentGroup.value.id // 假设群聊 ID 作为接收者 ID
  //   ) {

  //     currentGroup.value.messages.push({
  //       sender: contentObj.senderId,
  //       content: contentObj.content,
  //       time: new Date().toLocaleTimeString()
  //     });
  //   }
  // });
  
});

function sendMessage() {
  if (!newMessage.value.trim()) return;

  const content = {
    senderId: username.value,
    groupId: currentGroup.value.id,
    content: newMessage.value
  };
  console.log(content);

  const msg = {
    type: 1, // 群聊消息类型，根据实际情况调整
    content: JSON.stringify(content)
  };

  window.electronAPI.socket.send({
    type: '0x02', // 群聊，根据实际情况调整
    content: JSON.stringify(msg)
  });
  console.log("send-groupDetail.vue");

  currentGroup.value.messages.push({
    sender: username.value,
    content: newMessage.value,
    time: new Date().toLocaleTimeString()
  });

  newMessage.value = '';
}

function openEmojiPicker() {
  console.log('表情功能未实现');
}

function openFilePicker() {
  console.log('文件上传功能未实现');
}
</script>

<style scoped>
/* 设置所有元素使用 border-box 盒模型 */
*,
*::before,
*::after {
  box-sizing: border-box;
}
body {
  margin: 0;
  padding: 0;
}
.group-chat-room {
  height: 100vh;
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 0;
  overflow: hidden;
}
.chat-header {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}
.unread-count {
  color: red;
  margin-left: 10px;
}
.group-desc {
  font-size: 12px;
  color: #888;
  margin-left: 10px;
}
.chat-messages {
  flex: 0.95;
  overflow-y: auto;
  padding: 15px;
  background-color: #f9f9f9;
}
.chat-message {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
  position: relative;
}
.self-message {
  flex-direction: row-reverse;
}
.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin: 0 8px;
  flex-shrink: 0;
}
.message-wrapper {
  max-width: 75%;
  display: flex;
  flex-direction: column;
}
.message-sender {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
  margin-left: 8px;
}
.message-content {
  padding: 8px 12px;
  border-radius: 18px;
  position: relative;
  word-wrap: break-word;
  word-break: normal;
  overflow-wrap: break-word;
  white-space: pre-wrap;
  display: inline-block;
  max-width: 100%;
}
/* 他人消息样式 */
.chat-message:not(.self-message) .message-content {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
  margin-left: 8px;
}
/* 自己消息样式 */
.self-message .message-content {
  background-color: #95ec69; /* 绿色气泡 */
  color: #000; /* 黑色字体更清晰 */
  margin-right: 8px;
}
/* 消息气泡的箭头 */
.chat-message:not(.self-message) .message-content::before {
  content: '';
  position: absolute;
  left: -8px;
  top: 10px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid white;
}
.chat-message:not(.self-message) .message-content::after {
  content: '';
  position: absolute;
  left: -9px;
  top: 10px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-right: 8px solid #e0e0e0;
  z-index: -1;
}
.self-message .message-content::before {
  content: '';
  position: absolute;
  right: -8px;
  top: 10px;
  border-top: 8px solid transparent;
  border-bottom: 8px solid transparent;
  border-left: 8px solid #95ec69;
}
.message-time {
  font-size: 10px;
  color: #777;
  margin-top: 3px;
  text-align: right;
  padding: 0 8px;
}
.self-message .message-time {
  text-align: right;
}
.message-input-area {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-top: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}
.icon-section {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  justify-content: flex-start;
}
.input-and-send {
  flex: 1;
  display: flex;
  width: 100%;
}
.message-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  margin-right: 10px;
  resize: none;
}
.send-button {
  padding: 8px 12px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}
.send-button:hover {
  background-color: #0056b3;
}
.no-group-selected {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #777;
}
/* 图标样式 */
.fa-regular {
  font-size: 20px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 0;
}
/* 微笑图片样式 */
.smile-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin-right: 10px;
}
/* 文件上传图片样式 */
.file-upload-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin-right: 10px;
}
</style>